class UsersController < ApplicationController
  before_filter :login_required, :except => [:new, :create, :index, :show]
  before_filter :find_user, :except => [:index, :new, :create]

  # render new.rhtml
  def new
  end

  def create
    @user = User.new(params[:user])
    @user.save!
    self.current_user = @user
    redirect_back_or_default('/')
    flash[:notice] = "Thanks for signing up!"
  rescue ActiveRecord::RecordInvalid
    render :action => 'new'
  end

  def index
    @users = User.find(:all, :order => 'login')

    respond_to do |format|
      format.html
      format.xml  { render :xml => @users.to_xml(:only => [:id, :login, :email, :created_at]) }
    end
  end

  def show
    respond_to do |format|
      format.html {
        @pager = ::Paginator.new(Article.count_per_user(params[:id]), AppConstants::LIMIT) do |offset, per_page|
          Article.find_per_user(params[:id], offset, per_page)
        end
        @page = @pager.page(params[:page])
        @num_pages = Article.count_per_user(params[:id])/AppConstants::LIMIT + 1
      }  
      format.xml  { 
        offset = (params[:page] and params[:page].to_i > 1) ?
                 (params[:page].to_i - 1)*AppConstants::LIMIT : 0
        @articles = Article.find_per_user(params[:id], offset, AppConstants::LIMIT)
        render :xml => @articles.to_xml(:except => [:body, :user_id]) 
      }
    end
  end
    
  # GET /users/1;edit
  def edit
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
     respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = 'Users was successfully updated.'
        format.html { redirect_to user_url(@user) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors.to_xml }
      end
     end
  end

  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    @user.destroy

    respond_to do |format|
      format.html { redirect_to users_url }
      format.xml  { head :ok }
    end
  end

  # maps to /users/1;destroy
  # HTTP verb: GET
  # used when JS is disabled
  def delete
  end

protected
  def find_user
    @user = User.find(params[:id])
  end  

  def authorized?
    return true if ['index', 'new', 'create', 'show' ].include?(action_name)
    user = User.find(params[:id])
    current_user.login == user.login || current_user.login == 'admin'
  end

end
